<?php

namespace App\Http\Controllers\Users;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    // 登录页面
    public function index()
    {
        return view('user.login');
    }

    // 登录行为
    public function login(Request $request)
    {
        // 验证
        $rules = [
            'email' => 'required|min:4|email',
            'password' => 'required|min:6|max:16',
            'is_remember' => 'integer',
        ];
        $this->validate($request, $rules);

        // 保存
        $user = $request->only(['email', 'password']);
        $is_remember = boolval($request->input('is_remember'));
        if (Auth::attempt($user, $is_remember)) {
            return redirect('/posts');
        }

        // 渲染
        return redirect()->back()->withErrors(['用户名密码不正确']);
    }

    // 登出行为
    public function logout()
    {
        Auth::logout();
        return redirect('/user/login');
    }
}
